(function(){
	$.fn.extend({
		priceCalculator: function(options) {
			var that = $(this),
				totalPriceArr = [],
				counterEl,
				counter,
				config = {
					onchange: function(value) {}
				};
			if (typeof options == 'object') {
				$.extend(config, options);
			} else if (typeof options == 'String') {
				switch (options) {
					case 'destroy':
						destroy();
						break;
				}
			}
			$.each(that, function(index) {
				var $this = $(this),
					modifyBtn = $this.find('a');
				if ($this.is('input')) {
					counterEl = $this;
				} else {
					counterEl = $this.find('input');
				}
				modifyBtn.off('click');
				modifyBtn.on('click', function(e) {
					counter = counterEl.val();
					switch ($(this).index()) {
						case 0:
							counter--;
							if (counter < 0) {
								counter = 0;
							}
							break;
						case 2:
							counter++;
							break;
					}
					e.stopPropagation();
					counterEl.val(counter);
					config.onchange(counter);
					fireonchange(counterEl);
				})
				counterEl.on('keydown keyup', function(e) {
					var $this = $(this),
						counterVal = '',
						counter = 0,
						keycode = e.charCode ? e.charCode : e.keyCode;
					switch (e.type) {
						case 'keydown':
							if (keycode != 8 && keycode != 37 && keycode != 39 && keycode < 48 || keycode > 57 && keycode < 96 || keycode > 105) {
								e.preventDefault();
							} else if (keycode != 37 && keycode != 39) {
								$this.val() != 0 ? $this.val() != 0 : $this.val('');
							}
							break;
						case 'keyup':
							counterEl.val(counterEl.val().replace(/\D/g, ''))
							config.onchange();
							fireonchange(counterEl);
							break;
					}
				});
				counterEl.blur(function() {
					var $this = $(this),
						counter = counterEl.val();
					if ($this.val() == '') {
						$this.val(0)
					};
					config.onchange(counter);
				})
			});

			function destroy() {
				$.each(that, function(index) {
					$(this).find('a').unbind('click');
				});
			}

			function fireonchange(_this) {
				_this.trigger('onchange');
			}
		}
	})
})(jQuery)